<template>
  <div class="alphabet" ref="wrapper">
    <div>
      <ul class="alphabet-list">
        <li
          v-for="item of cityLetters"
          :key="item"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
          @click="handleLetterClick"
          :ref="item"
        >{{item}}</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
import axios from "axios";
export default {
  name: "Alphabet",
  data() {
    return {
      alphabet: {},
      touchStatus: false,
      startY: 0,
      timer: null // 函数执行次数截流,提高网页性能
    };
  },
  // 加载顺序
  updated() {
    this.startY = this.$refs["A"][0].offsetTop; //A距离本模块顶部的距离
  },
  created() {
    this.getAlphabetList();
  },
  methods: {
    getAlphabetList() {
      axios.get("/api/city.json").then(res => {
        this.alphabet = res.data.data.cities;
      });
    },
    // 获取事件对象
    handleLetterClick(e) {
      // 子传父
      this.$emit("change", e.target.innerText);
    },
    // 手指开始触摸
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          // this.startY = - (this.$refs['A'][0].offsetTop - 74)  //A距离本模块顶部的距离
          const touchY = e.touches[0].clientY - 80; // 手指距离本模块顶部的距离
          const index = Math.floor((touchY - this.startY) / 20) - 10 + 3; // 手指位置对应得字母下标
          // console.log(index);
          if (index >= 0 && index <= this.cityLetters.length) {
            this.$emit("change", this.cityLetters[index]); //  将动态的值传给 通过父组件传给相应的兄弟组件
          }
        },10);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  },
  // 计算属性
  computed: {
    // 方法名，即定义的变量
    cityLetters() {
      const Letters = [];
      for (let i in this.alphabet) {
        Letters.push(i);
      }
      return Letters;
    }
  },
  //js语法
  mounted() {
    //自定义滚动
    // this.scroll = new BScroll(this.$refs.wrapper)
    let scroll = new BScroll(this.$refs.wrapper, {
      scrollY: true,
      click: true
    });
  }
};
</script>
<style scoped>
.alphabet {
  position: fixed;
  top: 34%;
  right: 0px;
  bottom: 0;
}
.alphabet .alphabet-list {
  color: #00bcd4;
  width: 30px;
  /* background: red; */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.alphabet .alphabet-list li {
  height: 20px;
  line-height: 20px;
}
</style>